﻿# ---------------------------------------------------------------- #
# Active Directory Domain Services (ADDS) Permission Configuration #
# ---------------------------------------------------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing Active Directory permission '$($script.type)' configuration ... " -NoNewLine $true
$session = Get-VirtualMachineInstancePowerShellSession -Subscription $subscription -VirtualMachineName $virtualMachineName
switch ($script.type)
{
	"Grant"
	{
        foreach ($permission in $script.permissions.permission)
        {
		    Invoke-Command -Session $session -ScriptBlock {
		        param([string]$userName, [string]$name)
                $rootDSE = [ADSI]"LDAP://RootDSE"
                $defaultNamingContext = $rootDSE.defaultNamingContext
                $configurationNamingContext = $rootDSE.configurationNamingContext
                $userPrincipal = New-Object Security.Principal.NTAccount("$userName")
                DSACLS "$defaultNamingContext" /G "$($userPrincipal):CA;$name" | Out-Null
                DSACLS "$configurationNamingContext" /G "$($userPrincipal):CA;$name" | Out-Null
		    } -ArgumentList $script.userName, $permission.name
        }
	}
	default
	{
		throw "Active Directory permission type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."